import { getToken } from './vmeitime-http/localStorage'
import graceJS from "@/Grace6/js/grace.js";
const nowTime = () => parseInt( (new Date().getTime() / 1000)) // 现在的时间戳
class socketIO {
	
	constructor(){
		this.connceted = false // 是否已连接
		this.locking = false
		this.last_request_time = nowTime()
		this.queue_length = 0
		this.queueing  = false
		this.is_destroy = false
		uni.onSocketOpen(this.onOpen.bind(this))
		uni.onSocketMessage(this.onMessage.bind(this))
		uni.onSocketClose(this.onClose.bind(this))
	}
	
  static that () { // 当前实例
	if (!this.instance) {
	console.log("init")
	  this.instance =  new socketIO() 
	}
	return this.instance
  }
	  	  
	// construct函数不能用异步 因此创建此函数代替
	async initConfig(){
		this.socketTask = null
		this.url = `wss://ylc.duyumy.com/ws_proxy?token=${encodeURIComponent(await getToken())}` //连接地址
		this.timeout = 3000 //多少秒执行检测
	}
	 
	// 进入这个页面的时候创建websocket连接【整个页面随时使用】
	async connectSocketInit() {
		await this.initConfig()
		return new Promise(resolve => {
			uni.connectSocket({
				url: this.url,
				complete: () => setTimeout(() =>resolve('创建链接'), 5000),
			//	timeout:2000
			});
		})
	}
	onOpen(res) {
		console.log('open')
		console.log(res)
		this.connceted = true
		this.queueing = false
		getApp().globalData.line = true
	}
	async onClose(e) {  // 注意 这里本身就是个递归  连接不上也会出发这个事件的
		console.log(e)
		this.connceted = false
		getApp().globalData.line = false
		if(this.queueing === false){
			await this.runQueueConnection()
		}
	}
	
	onMessage(e) {
		let res = JSON.parse(e.data);
		console.log("res---------->", e.data) // 这里 查看 推送过来的消息
		uni.$emit('getPositonsOrder', res);
	}
	
	async runQueueConnection(){
		if(this.is_destroy){
			return
		}
		this.queueing = true
		while(this.connceted === false && (!this.is_destroy)){ // 死循环连接 直至成功
			console.log(this.connceted)
			await this.connectSocketInit() // connectSocketInit延迟一秒了 所以每秒连接一次
		}
	}
	destroy(){ // 抛弃当前实例 解决切出去的bug
		uni.closeSocket()
		this.is_destroy = true
	}
}

export default socketIO
